import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:wch/model/login_custom.dart';
import 'package:wch/native/net_business.dart';
import '../constant/config_constant.dart';
import '../constant/event_bus_global.dart';
import '../utils/digital_utils.dart';
import '../utils/loading_utils.dart';
import '../utils/navigator_utils.dart';
import '../utils/toast_utils.dart';
import '../widget/common_widget.dart';
import '../widget/login_widget.dart';
import '../widget/protocol_widget.dart';
import '../widget/text_widget.dart';
import '../widget/padding_widget.dart';
import '../constant/resource_constant.dart';
import '../constant/text_constant.dart';
//
//忘记密码
//
class ForgetPassPage extends StatefulWidget {
  const ForgetPassPage({Key? key}) : super(key: key);
  @override
  State<ForgetPassPage> createState() => _ForgetPassPageState();
}

class _ForgetPassPageState extends State<ForgetPassPage> {
  ///登录实体
  late LoginCustomModel loginEntity;
  ///获取登录实体
  LoginCustomModel getLoginEntity() {
    loginEntity = LoginCustomModel();
    return loginEntity;
  }
  final FocusNode _phoneFocusMode = FocusNode();
  final FocusNode _codeFocusMode = FocusNode();
  final FocusNode _passFocusMode = FocusNode();
  final FocusNode _confirmPassFocusMode = FocusNode();

  @override
  Widget build(BuildContext context) {
    return KeyboardDismissOnTap(
      child: CommonScaffold(
        title: '忘记密码',
        body: Material(
          child: SingleChildScrollView(
            child: ChangeNotifierProvider(
              create: (_) => getLoginEntity(),
              child: Consumer<LoginCustomModel>(builder: (context, model, widget) {
                return KeyboardDismissOnTap(
                  child: LoginContainer(
                    horPadding: 15.w,
                    verTopPadding: 15.h,
                    verBottomPadding: 15.h,
                    backgroundColor: Color(0xFFF8F9FB),
                    child: Container(
                      padding: EdgeInsets.symmetric(horizontal: 30.w, vertical: 40.h),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(7.5.h))
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          VerPadding(5.h),
                          InputMobile(callback: (index, num){
                            model.name = num;
                            notifyBtnState(model);
                            notifySendCodeState(model);
                          }, hintText: inputPhoneHint2, focusNode: _phoneFocusMode,),
                          InputValidCode(callback: (index, num) {
                            if (index == -1) {
                              _sendCodeLogic(model);
                            }
                            model.code = num;
                            notifyBtnState(model);
                          }, isEnabled: model.isMobileValid, node: _codeFocusMode,),
                          InputPass(callback: (index, num) {
                            model.pass = num;
                            notifyBtnState(model);
                          }, title: inputPassHint2, node: _passFocusMode,),
                          InputPass(callback: (index, num) {
                            model.confirmPass = num;
                            notifyBtnState(model);
                          }, title: inputConfirmPassHint, node: _confirmPassFocusMode,),
                          VerPadding(33.0.h),
                          CommonBtn(title: finishText, isEnable: model.btnEnable, callback: (){
                            clickBtnLogic(model);
                          },),
                          Expanded(child: Container()),
                        ],
                      ),
                    ),
                  ),
                );
              }),
            ),
          ),
        ),
      ),
    );
  }

  void clickProtocol(LoginCustomModel entity) {
    entity.isAgree = !entity.isAgree;
    entity.update();
  }
  ///点击了确定按钮
  void clickBtnLogic(LoginCustomModel entity) {

    _phoneFocusMode.unfocus();
    _codeFocusMode.unfocus();
    _passFocusMode.unfocus();
    _confirmPassFocusMode.unfocus();

    if (!entity.btnEnable) {
      return;
    }

    if (entity.name == null || entity.name!.isEmpty || entity.name!.length < 11) {
      ToastUtils.showToast(msg: checkMobileLen);
      return;
    }

    if (!DigitalUtils.chinaPhoneNumber(entity.name!)) {
      ToastUtils.showToast(msg: checkMobileValid);
      return;
    }

    if (entity.pass == null || entity.pass!.isEmpty || entity.pass!.length < 6) {
      ToastUtils.showToast(msg: checkPassValid);
      return;
    }

    if (entity.confirmPass == null || entity.confirmPass!.isEmpty || entity.confirmPass!.length < 6) {
      ToastUtils.showToast(msg: checkPassValid);
      return;
    }

    if (entity.pass! != entity.confirmPass!) {
      ToastUtils.showToast(msg: passNotSame);
      return;
    }

    if (entity.code == null || entity.code!.isEmpty || entity.code!.length != 6) {
      ToastUtils.showToast(msg: checkCodeValid);
      return;
    }

    // if (!entity.isAgree) {
    //   ToastUtils.showToast(msg: needSelectProtocol);
    //   return;
    // }

    Loading.getIns().loading(msg: '正在修改密码');
    NetBusiness().setPass(memberMobile: entity.name!, verifyCode: entity.code!, memberPassword: entity.pass!).then((value) {
      Loading.getIns().hide();
      if (value) {
        ToastUtils.showToast(msg: '密码修改成功');
        NavigatorUtil.pop(context);
      }
    });
  }
  ///更新按钮状态
  void notifyBtnState(LoginCustomModel entity) {
    if (entity.name == null || entity.name!.isEmpty) {
      entity.btnEnable = false;
      return;
    }

    if (entity.pass == null || entity.pass!.isEmpty) {
      entity.btnEnable = false;
      return;
    }

    if (entity.confirmPass == null || entity.confirmPass!.isEmpty) {
      entity.btnEnable = false;
      return;
    }

    if (entity.code == null || entity.code!.isEmpty) {
      entity.btnEnable = false;
      return;
    }

    entity.btnEnable = true;
    entity.update();
  }
  ///输入手机是否合法，通过此判断发送验证码按钮的可用性
  void notifySendCodeState(LoginCustomModel entity) {
    if (entity.name == null) {
      entity.isMobileValid = false;
    } else if (entity.name!.length < 11) {
      entity.isMobileValid = false;
    } else if (!DigitalUtils.chinaPhoneNumber(entity.name!)) {
      entity.isMobileValid = false;
    }

    entity.isMobileValid = true;
    entity.update();
  }
  ///发送验证码
  void _sendCodeLogic(LoginCustomModel entity) {
    Loading.getIns().loading(msg: '正在发送验证码');
    NetBusiness().sendCode(codeType: 'RESET', mobile: entity.name!).then((value) {
      Loading.getIns().hide();
      if (value) {
        ToastUtils.showToast(msg: '已发送验证码，请查收');
        globalEventBus.fire(RefreshSendCodeModel());
      }
    });
  }
}
